package github.flandre.examplemod.network.Packet;

import github.flandre.examplemod.common.mycapability.ISpeedUpCapability;
import github.flandre.examplemod.core.registry.CommonSetupEventHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.ClientPlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.NetworkEvent;

import java.util.function.Supplier;

public class Power {
    public float power;

    public Power() {
    }

    public Power(float power) {
        this.power = power;
    }

    public float getPower() {
        return power;
    }

    //通过这两个函数序列化和反序列化
    public static void encode(Power p, PacketBuffer buffer)
    {
        buffer.writeFloat(p.power);
    }

    public static Power decode(PacketBuffer buffer)
    {
        return new Power(buffer.readFloat());
    }
    //服务器处理逻辑
    public static void handlePacket(Power p, Supplier<NetworkEvent.Context> content)
    {
        NetworkEvent.Context context = content.get();
        context.enqueueWork(()->{
           onClientCustomPack(p);
        });
        context.setPacketHandled(true);
    }


    //这个代码仅在客户端作用
    @OnlyIn(Dist.CLIENT)
    public static void onClientCustomPack(Power p) {
        //p中包含服务器的数值，传到客户端中
        Minecraft mc = Minecraft.getInstance();
        ClientPlayerEntity player = mc.player; //客户端对象
        assert player != null;
        LazyOptional<ISpeedUpCapability> capability = player.getCapability(CommonSetupEventHandler.SPEED_UP_CAPABILITY);
        capability.ifPresent((c)->{
            c.setLevel(p.getPower());
        });
    }
}
